package com.gym.service.user.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.gym.VO.ResultVO;
import com.gym.constant.Constant;
import com.gym.converter.RegisterForm2UserBaseInfoDTOConverter;
import com.gym.converter.RegisterForm2UserDetailInfoConvert;
import com.gym.dto.user.UserBaseInfoDTO;
import com.gym.enums.ResultEnum;
import com.gym.form.user.RegisterForm;
import com.gym.pojo.user.UserBaseInfo;
import com.gym.pojo.user.UserDetailInfo;
import com.gym.pojo.user.UserRole;
import com.gym.service.user.RegisterService;
import com.gym.service.user.UserRoleService;
import com.gym.service.user.UserService;
import com.gym.utils.ResultVOUtil;

@Service
public class RegisterServiceImpl implements RegisterService {

	@Autowired
	private UserService userService;

	@Autowired
	private UserRoleService userRoleService;

	@Override
	public ResultVO register(RegisterForm registerForm) {
		UserBaseInfoDTO userBaseInfoDTO = RegisterForm2UserBaseInfoDTOConverter
				.convert(registerForm);

		// 添加用户基本信息
		ResultVO addBaseInfoResult = this.userService
				.addUserBaseInfo(userBaseInfoDTO);

		if (addBaseInfoResult.getCode() != 0) {
			return addBaseInfoResult;
		}

		UserDetailInfo userDetailInfo = RegisterForm2UserDetailInfoConvert
				.convert(registerForm);

		UserBaseInfo userBaseInfo = (UserBaseInfo) addBaseInfoResult.getData();

		userDetailInfo.setUserId(userBaseInfo.getUserId());

		// 添加用户详细信息
		ResultEnum addDetailInfoResult = this.userService
				.addUserDetailInfo(userDetailInfo);

		if (addDetailInfoResult.getCode() != 0) {
			this.userService.deleteUserBaseInfo(userBaseInfo.getUserId());
			return ResultVOUtil.error(addDetailInfoResult);
		}

		// 添加用户角色-学生
		UserRole userRole = new UserRole();
		userRole.setUserId(userBaseInfo.getUserId());
		userRole.setRoleId(Constant.DEFAULT_USER_ROLE_ID);
		this.userRoleService.addUserRole(userRole);

		return ResultVOUtil.success();

	}
}
